﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ChholCmdPort;

namespace ChholConfig {
	public partial class PortUserForm : Form, IPortUserUI {
		public PortUserForm() {
			InitializeComponent();
		}
		public Bitmap Bmp { get; protected set; }
		private string port_text;
		public PortUserHandle Port_user { get; protected set; }

		public Image Icon_image => Bmp;
		public event EventHandler ePortNameChanged;
		public event EventHandler eClosed;

		public string Port_text {
			get => port_text;
			protected set {
				port_text = value;
				ePortNameChanged?.Invoke(this, EventArgs.Empty);
			}
		}

		public PortUserForm(Bitmap bmp, byte default_port, RecvFanOut fan_out, string port_name) {
			this.Bmp = bmp;
			this.Port_text = port_name;
			InitializeComponent();
			this.Icon = Icon.FromHandle(bmp.GetHicon());
			this.Port_user = fan_out.createPortUser();
			this.potrNumTB.Text = default_port.ToString();
			ePortNameChanged += (s, e) => this.Name = this.Text = this.getPortName();
			ePortNameChanged.Invoke(this, EventArgs.Empty);
		}
		virtual public void showForm() {
			this.Show();
			this.WindowState = FormWindowState.Normal;
			this.Focus();
		}
		virtual public void forceClose() {
			this.OnClosing(new CancelEventArgs());
		}
		protected override void OnClosing(CancelEventArgs e) {
			base.OnClosing(e);
			Port_user.stop();
			eClosed?.Invoke(this,EventArgs.Empty);
		}

		private void clickToConnect(object sender, EventArgs e) {
			byte id = byte.Parse(potrNumTB.Text);
			if (Port_user.Run(id)) {
				potrNumTB.BackColor = Color.WhiteSmoke;
				ePortNameChanged?.Invoke(this,EventArgs.Empty);
				TopTS.Visible = false;
				turnOn();

			} else {
				potrNumTB.BackColor = Color.LightPink;
			}
		}
		protected virtual void turnOn() {
		}
	}
}
